package jp.reflexworks.gae.blogger;

import java.io.IOException;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import jp.reflexworks.gae.blogger.model.Product;
import jp.reflexworks.gae.util.KeyUtils;
import jp.reflexworks.gae.util.PMF;

@SuppressWarnings("serial")
public class BloggerServlet extends HttpServlet {
	Logger logger = Logger.getLogger(this.getClass().getName());
	
	//singleton
	//Blogger blogger = Blogger.getInstance();

	
	//vtecadmin
	private static final String BLOG_ID = "7726217364309932343";
	private static final String PROFILE_ID = "07431124518582514230";
//	//vtecdemo
//	private static final String BLOG_ID = "3414129485798227244";
//	private static final String PROFILE_ID = "11047747929288976014";	
	
	private static final String EMAIL = "vtecadmin@gmail.com";
	private static final String PASSWORD = "vtec2009";
	
	
	
	
	
	
	
	
	//ClientLogin
	Blogger blogger = new Blogger(BLOG_ID, EMAIL, PASSWORD);

	//AuthSub
	//	Blogger blogger = new Blogger(BLOG_ID);
	
	/*
	 * MEMO
	 * ユーザーをvtecdemo以外で認証をかけると「Invalid content type: defaults」
	 */

	
	
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {

		
		String tokenAuth;
		
		if (req.getParameter("init") != null) {
			
			for (int i = 0; i < 3; i++) {
			
				Product product = new Product();
				
				String janCode = "123456789012" + i;
				String mkCode = "makercode00" + i;
				long revision = 1;
				String strKey = mkCode + "_" +  janCode + "_" + revision; 
				
				Key key = KeyFactory.createKey(Product.class.getSimpleName(), strKey);
				product.setKey(key);
				
				product.setJanCode(janCode);
				product.setMkCode(mkCode);
				product.setRevision(revision);
				
				PersistenceManager pm = PMF.get().getPersistenceManager();
				
				pm.makePersistent(product);
			}
			
			res.setContentType("text/plain; charset=UTF-8");
			res.getWriter().println("init");
			
		} else if (req.getParameter("clientlogin") != null) {
			//ClientLogin
			blogger.clientLogin();
			res.sendRedirect("/post.html");
			
		} else if ((tokenAuth = req.getParameter("token")) != null) {
			
			//AuthSub			
			log("tokenAuth=" + tokenAuth);
			blogger.setTokenAuth(tokenAuth);
			blogger.setAuthSubSessionToken();
			res.sendRedirect("/post.html");
	
			
//			//AuthSub
//			String tokenAuth;
//			
//			if ((tokenAuth = req.getParameter("token")) != null) {			
//				log("tokenAuth=" + tokenAuth);
//				blogger.setTokenAuth(tokenAuth);
//				blogger.setAuthSubSessionToken();
//				res.sendRedirect("/post.html");
//			} else {
//				res.setContentType("text/plain");
//				res.getWriter().println("Hello, blogger");
//			}
			
		} else if (req.getParameter("products") != null) {	
			
			PersistenceManager pm = PMF.get().getPersistenceManager();
			
			int i = 0;
			String janCode = "123456789012" + i;
			String mkCode = "makercode00" + i;
			long revision = 1;
			String strKey = mkCode + "_" +  janCode + "_" + revision; 
			
			Key key = KeyFactory.createKey(Product.class.getSimpleName(), strKey);
			Product product = pm.getObjectById(Product.class, key);
			
			
			
			
			String title = product.getJanCode();
			String content = product.getJanCode() + " / " + product.getMkCode() + " / " + product.getRevision();
			String label = "test";
			
			pm.close();
			
			blogger.clientLogin();
			
			String atom = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entry xmlns='http://www.w3.org/2005/Atom'><title type='text'>" + title + "</title><content type='xhtml'><div xmlns=\"http://www.w3.org/1999/xhtml\">" + content +"</div></content><category scheme=\"http://www.blogger.com/atom/ns#\" term=\"" + label + "\" /></entry>";
			String result = blogger.post(atom);
			
			res.setContentType("text/plain");
			res.getWriter().println(result);
			
		} else {
			res.setContentType("text/plain; charset=UTF-8");
			
			res.getWriter().println("Hello, blogger B");
		}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
		
		String title = req.getParameter("title");
		if (title == null) {
			title = "defaultTitle";
		}
		
		String content = req.getParameter("content");
		if (content == null) {
			content = "defaultContent";
		}

		String label = req.getParameter("label");
		if (label == null) {
			label = "defaultLabel";
		}
		
		//NOTE URLEncoder.encode(title, "UTF-8")等は必要ない

		
		//TODO reflexで作る
		//TODO atomの構造
		String atom = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entry xmlns='http://www.w3.org/2005/Atom'><title type='text'>" + title + "</title><content type='xhtml'><div xmlns=\"http://www.w3.org/1999/xhtml\">" + content +"</div></content><category scheme=\"http://www.blogger.com/atom/ns#\" term=\"" + label + "\" /></entry>";
		String result = blogger.post(atom);

//		String result = null;
//		for (int i = 0; i < 10; i++) {
//			atom = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entry xmlns='http://www.w3.org/2005/Atom'><title type='text'>title_" + i + "</title><content type='xhtml'><div xmlns=\"http://www.w3.org/1999/xhtml\">" + content +"</div></content><category scheme=\"http://www.blogger.com/atom/ns#\" term=\"" + label + "\" /></entry>";
//			result = blogger.post(atom);
//			log("post count: " + i);
//			log(result);
//			
//		}
		
		
		
		res.setContentType("text/html; charset=UTF-8");
		res.getWriter().print("<h1>多分投稿できました</h1>\n<a href=\"http://vtecdemo.blogspot.com/\">http://vtecdemo.blogspot.com/</a><br>\n<a href=\"http://vtecadmin.blogspot.com/\">http://vtecadmin.blogspot.com/</a><!--" + result + "-->");
		
	}
	
	private void log(Object o) {
		logger.severe(o.toString());
		System.out.println(o);
	}

}
